package com.zytlifeservice.service.find;

import com.zytlifeservice.domain.User;
import com.zytlifeservice.domain.find.IntegralOrder;
import com.zytlifeservice.exception.UserException;
import com.zytlifeservice.repository.UserRepository;
import com.zytlifeservice.repository.find.IntegralOrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 积分订单业务类
 * Created by Administrator on 2017/6/1.
 */
@Service
public class IntegralOrderService {
    @Autowired
    private IntegralOrderRepository integralOrderRepository;

    @Autowired
    UserRepository userRepository;


    //添加兑换积分商品订单--在下单时用上
    @Transactional
    public Integer addIntegralOrder(IntegralOrder integralOrder) {
        Integer result = 0;
        try {
            integralOrderRepository.save(integralOrder);
            result = 1;
        } catch (Exception ex) {
            result = 0;
            ex.printStackTrace();
        }
        return result;
    }

    //修改兑换积分商品订单
    @Transactional
    public Integer updateIntegralOrder(IntegralOrder integralOrder) {
        Integer result = 0;
        try {
            integralOrderRepository.save(integralOrder);
            result = 1;
        } catch (Exception ex) {
            result = 0;
            ex.printStackTrace();
        }
        return result;
    }

    //查询单个兑换积分商品订单
    public IntegralOrder findOddIntegralOrder(Long id) {
        return integralOrderRepository.getOne(id);
    }

    //删除订单
    @Transactional
    public Integer deleteIntegralOrder(Long id) {
        Integer result = 0;
        try {
            integralOrderRepository.delete(id);
            result = 1;
        } catch (Exception ex) {
            result = 0;
            ex.printStackTrace();
        }
        return result;
    }

    //查询个人订单
    public List<IntegralOrder> findUserAll(Long userId) {
        User one = userRepository.findOne(userId);
        if (one == null) {
            throw new UserException("用户不存在", 202);
        }
        return integralOrderRepository.findAllByUserIdOrderByCreateDateDesc(userId);
    }

    public Object findCustom() {
        return integralOrderRepository.findCustomDatas();
    }


    public void delete(long userId, long id) {
        User one = userRepository.findOne(userId);
        if (one == null) {
            throw new UserException("用户不存在", 202);
        }
        integralOrderRepository.delete(id);
    }

}
